<script setup>
import { ref, reactive, computed } from "vue";
import { useAreaStore } from "@/stores/area";
import { useCompanyStore } from "@/stores/company";
import { handleError } from "@/utils/handleError";
import {
  addMergedAreaApi,
  deleteMergedAreaApi,
  updateAreaApi,
  updateMergedAreaApi
} from "../../../../../api/area";

// 初始化状态管理
const areaStore = useAreaStore();
const companyStore = useCompanyStore();

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  nodes: {
    type: Object,
    default: () => ({
      single_area: [],
      merged_area: []
    })
  }
});

// 定义事件
const emit = defineEmits(["update:visible", "merge-areas", "update-ratio", "unmerge-area", "refresh"]);

// 加载状态
const mergeLoading = ref(false);
const updateLoading = ref(false);
const unmergeLoading = ref(false);

// 计算属性：合并区域包含的子区域映射
const mergedAreaMembers = computed(() => {
  const result = {};
  if (!Array.isArray(areaStore.areas)) return result;

  areaStore.areas.forEach(area => {
    if (area?.merged_area) {
      if (!result[area.merged_area]) {
        result[area.merged_area] = [];
      }
      const areaName = areaStore.getAreaNameById(area.id);
      if (areaName) {
        result[area.merged_area].push(areaName);
      }
    }
  });
  return result;
});

// 数据处理函数：格式化区域数据
const processAreaData = (area, isMerged = false) => {
  if (!area) return null;

  const drainageRatio = parseFloat(area.ratio || '0');
  const areaId = isMerged ? area.merged_area_id : area.area_id;
  const label = isMerged
    ? areaStore.getMergedAreaNameById(area.merged_area_id)
    : areaStore.getAreaNameById(area.area_id);

  return {
    ...area,
    area_id: areaId,
    label: label || '未命名区域',
    vi: parseFloat(area.vi || '0'),
    vco: parseFloat(area.vco || '0'),
    vd: parseFloat(area.vd || '0'),
    drainageRatio,
    consumptionRatio: Math.max(0, Math.min(1, 1 - drainageRatio)),
    mergedAreas: isMerged ? mergedAreaMembers.value[area.merged_area_id] || [] : []
  };
};

// 计算独立节点列表
const independentNodes = computed(() => {
  if (!Array.isArray(props.nodes?.single_area)) return [];
  return props.nodes.single_area
    .map(area => processAreaData(area))
    .filter(Boolean);
});

// 计算合并节点列表
const mergedNodes = computed(() => {
  if (!Array.isArray(props.nodes?.merged_area)) return [];
  return props.nodes.merged_area
    .map(area => processAreaData(area, true))
    .filter(Boolean);
});

// 计算可用于合并的区域列表
const availableAreas = computed(() => {
  return independentNodes.value.map(node => ({
    label: node.label,
    value: node.area_id
  }));
});

// 合并对话框状态
const mergeDialogVisible = ref(false);
const mergeForm = reactive({
  name: "",
  selectedAreas: [],
  drainageRatio: 0.9, // 添加了默认排水比例
});

// 合并表单验证
const validateMergeForm = () => {
  if (!mergeForm.name?.trim()) {
    ElMessage.warning('请输入合并区域名称');
    return false;
  }
  if (!Array.isArray(mergeForm.selectedAreas) || mergeForm.selectedAreas.length < 2) {
    ElMessage.warning('请至少选择两个区域进行合并');
    return false;
  }
  return true;
};

// 调整合并区域的排水比例
const adjustMergeRatio = (value) => {
  mergeForm.drainageRatio = Math.max(0, Math.min(1, parseFloat(value.toFixed(2))));
};

// 保存合并配置
const saveMergeConfig = async () => {
  if (!validateMergeForm()) return;

  mergeLoading.value = true;
  try {
    const params = {
      name: mergeForm.name.trim(),
      company_id: companyStore.currentCompany?.id,
      area_ids: mergeForm.selectedAreas,
      ratio: mergeForm.drainageRatio // 添加排水比例参数
    };

    const res = await addMergedAreaApi(params);
    if (res?.code === 200) {
      ElMessage.success('合并区域创建成功');
      await areaStore.fetchAreas();
      emit("refresh");
      resetMergeForm();
    } else {
      ElMessage.error(res?.message || '创建失败');
    }
  } catch (error) {
    console.error('添加合并区域失败:', error);
    handleError(error);
  } finally {
    mergeLoading.value = false;
    mergeDialogVisible.value = false;
  }
};

// 重置合并表单
const resetMergeForm = () => {
  mergeForm.name = "";
  mergeForm.selectedAreas = [];
  mergeForm.drainageRatio = 0.9; // 重置为默认值
};

// 编辑比例的状态管理
const editingNode = ref(null);
const editDialogVisible = ref(false);
const editedRatio = ref(0);

// 打开比例编辑对话框
const openRatioEdit = (node) => {
  if (!node) return;
  editingNode.value = node;
  editedRatio.value = node.drainageRatio;
  editDialogVisible.value = true;
};

// 保存比例修改
const saveRatioChanges = async () => {
  if (!editingNode.value) return;

  updateLoading.value = true;
  try {
    const isMerged = 'merged_area_id' in editingNode.value;
    const api = isMerged ? updateMergedAreaApi : updateAreaApi;
    const params = {
      id: isMerged ? editingNode.value.merged_area_id : editingNode.value.area_id,
      ratio: Math.max(0, Math.min(1, editedRatio.value))
    };

    await api(params);
    await areaStore.fetchAreas();
    ElMessage.success("修改成功");
    emit("refresh");
  } catch (error) {
    handleError(error);
  } finally {
    updateLoading.value = false;
    cancelRatioEdit();
  }
};

// 取消比例编辑
const cancelRatioEdit = () => {
  editDialogVisible.value = false;
  editingNode.value = null;
  editedRatio.value = 0;
};

// 解除区域合并
const unmergeArea = async (mergedNode) => {
  if (!mergedNode?.merged_area_id) return;

  unmergeLoading.value = true;
  try {
    await deleteMergedAreaApi({ id: String(mergedNode.merged_area_id) });
    await areaStore.fetchAreas();
    ElMessage.success("解除合并成功");
    emit("refresh");
  } catch (error) {
    handleError(error);
  } finally {
    unmergeLoading.value = false;
  }
};

// 关闭抽屉并重置状态
const handleClose = () => {
  emit("update:visible", false);
  editingNode.value = null;
  cancelRatioEdit();
  resetMergeForm();
};
</script>
<template>
  <el-drawer :model-value="visible" @update:model-value="handleClose" :with-header="false" direction="rtl" size="500px"
    destroy-on-close>
    <div class="drawer-content">
      <div class="section">
        <div class="header">
          <h3 class="section-title">区域配置管理</h3>
          <el-button type="primary" @click="mergeDialogVisible = true">新建合并</el-button>
        </div>

        <!-- 新建合并区域对话框 -->
        <el-dialog v-model="mergeDialogVisible" title="新建合并区域" width="500px" destroy-on-close>
          <el-form :model="mergeForm" label-width="80px">
            <el-form-item label="区域名称">
              <el-input v-model="mergeForm.name" placeholder="请输入合并后的区域名称" />
            </el-form-item>

            <el-form-item label="选择区域">
              <el-select filterable v-model="mergeForm.selectedAreas" multiple placeholder="请选择要合并的区域"
                style="width: 100%">
                <el-option v-for="area in availableAreas" :key="area.value" :label="area.label" :value="area.value" />
              </el-select>
            </el-form-item>
          </el-form>

          <el-form-item label="排水比例">
            <el-input-number v-model="mergeForm.drainageRatio" :min="0" :max="1" :precision="2" :step="0.1"
              controls-position="right" @change="adjustMergeRatio" />
            <div class="ratio-tip">耗水比例：{{ (1 - mergeForm.drainageRatio).toFixed(2) }}</div>
          </el-form-item>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="mergeDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveMergeConfig">确认</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 合并区域列表 -->
        <template v-if="mergedNodes.length > 0">
          <div class="section-subheader">
            <h4 class="subsection-title">合并区域</h4>
          </div>
          <div class="areas">
            <el-card v-for="node in mergedNodes" :key="node.area_id" class="area-card">
              <template #header>
                <span class="area-name">{{ node.name || node.label }}</span>
                <div class="header-actions">
                  <el-button link type="primary" @click="openRatioEdit(node)">
                    编辑比例
                  </el-button>
                  <el-popconfirm title="确定要解除该区域的合并吗？" @confirm="unmergeArea(node)">
                    <template #reference>
                      <el-button link type="danger">
                        解除合并
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
              <div class="area-info">
                <div class="area-stats">
                  <div class="stat-item">
                    <span class="stat-label">总流量：</span>
                    <span class="stat-value">{{ node.vi }}㎥</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">排水比例：</span>
                    <span class="stat-value">{{ node.drainageRatio.toFixed(2) }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">耗水比例：</span>
                    <span class="stat-value">{{ node.consumptionRatio.toFixed(2) }}</span>
                  </div>
                </div>
                <div class="merged-areas">
                  <div class="merged-areas-title">包含区域：</div>
                  <el-tag v-for="area in node.mergedAreas" :key="area" size="small" class="merged-area-tag">
                    {{ area }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </div>
        </template>

        <!-- 独立区域列表 -->
        <div class="section-subheader">
          <h4 class="subsection-title">独立区域</h4>
        </div>
        <div class="areas">
          <el-card v-for="node in independentNodes" :key="node.area_id" class="area-card">
            <template #header>
              <span class="area-name">{{ node.label }}</span>
              <el-button link type="primary" @click="openRatioEdit(node)">
                编辑比例
              </el-button>
            </template>
            <div class="area-stats">
              <div class="stat-item">
                <span class="stat-label">总流量：</span>
                <span class="stat-value">{{ node.vi }}㎥</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">排水比例：</span>
                <span class="stat-value">{{ node.drainageRatio.toFixed(2) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">耗水比例：</span>
                <span class="stat-value">{{ node.consumptionRatio.toFixed(2) }}</span>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 编辑比例对话框 -->
    <el-dialog v-model="editDialogVisible" :title="`编辑${editingNode?.label || ''}比例配置`" width="500px"
      @close="cancelRatioEdit">
      <div class="ratio-form">
        <div class="ratio-row">
          <div class="ratio-item">
            <span class="label">耗水比例</span>
            <div class="ratio-value">{{ (1 - editedRatio).toFixed(2) }}</div>
          </div>
          <div class="ratio-item">
            <span class="label">排水比例</span>
            <el-input-number v-model="editedRatio" :min="0" :max="1" :precision="2" :step="0.1"
              controls-position="right" />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRatioEdit">取消</el-button>
          <el-button type="primary" @click="saveRatioChanges">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<style scoped>
.drawer-content {
  height: 100%;
  padding: 20px;
  overflow-y: auto;
}

.section {
  margin-bottom: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin: 0;
}

.section-subheader {
  margin: 20px 0 12px;
}

.subsection-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-regular);
  margin: 0;
}

.areas {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.area-card {
  margin-bottom: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.area-name {
  font-weight: 500;
}

.area-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.area-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 13px;
  color: var(--el-text-color-regular);
}

.stat-value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.merged-areas {
  margin-top: 8px;
}

.merged-areas-title {
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin-bottom: var(--gap-small);
}

.merged-area-tag {
  margin-right: var(--gap-small);
}

.ratio-form {
  padding: 0 20px;
}

.ratio-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.ratio-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 180px;
}

.ratio-value {
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  text-align: center;
}

.ratio-tip {
  margin-left: var(--gap-normal);
  color: var(--el-text-color-regular);
}

.label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>